package com.wang.sort;
//数组小和问题(利用递归归并实现)
//在一个数组中，一个数左边比它小的数的总和，叫数的小和，所有数的小和累加起来,叫数组小和
public class Demo17_SmallSum {
    public static int smallSum(int[] arr) {
        if(arr == null || arr.length < 2) {
            return 0;
        }
        return process(arr, 0, arr.length - 1);
    }
    private static int process(int[] arr, int L, int R) {
        //base case
        if(L == R) {
            return 0;
        }
        int mid = L + ((R - L) >> 1);
        process(arr, L, mid);
        process(arr, mid + 1, R);
        merge(arr, L, mid, R);
        return process(arr, L, mid)
                + process(arr, mid + 1, R)
                + merge(arr, L, mid, R);

    }
    public static int merge(int[] arr, int L, int mid, int R) {
        int[] help = new int[R - L + 1];
        int i = 0;
        int p1 = L;
        int p2 = mid + 1;
        int res = 0;//小和
        //循环条件 p1 p2不越界
        while (p1 <= mid && p2 <= R) {
            //小和累加
            res += arr[p1] < arr[p2] ? (R - p2 + 1) * arr[p1] : 0;
            help[i++] = arr[p1] < arr[p2] ? arr[p1++] : arr[p2++];
        }
        //要么p1越界，要么p2越界
        //p1未越界，把p2剩余元素放到help
        //p2未越界，把p1剩余元素放到help
        while (p1 <= mid) {
            help[i++] = arr[p2++];
        }
        while (p2 <= mid) {
            help[i++] = arr[p1++];
        }
        //把help数组刷回原数组
        for (int j = 0; j < help.length; j++) {
            arr[L + i] = help[i];
        }
        return res;
    }
}
